<?php

namespace App\Http\Controllers\Api;

use App\Api\Filters\BookCollectionFilter;
use App\Models\BookCollection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;

use App\Http\Resources\BookCollection as BookCollectionResource;

class BookCollectionController extends ApiController
{


    public function __construct()
    {
        $this->middleware('auth:api')->only([
            'store',
            'destroy'

        ]);
    }


    /**
     *
     * @api {get} /book_collections 获取书单列表
     * @apiName Books get book_collections
     * @apiGroup BookCollection
     *
     * @apiParam {String} [me] 获取自己的书单
     * @apiParam {String} [gender] 0=> 男频，1=>女频，不传为全部
     * @apiParam {String} [limit] 限制的条数
     * @apiParam {String} [page] 当前的页数
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/book_collections
     *
     */
    public function index(Request $request,BookCollectionFilter $filters){


        $book_collection = $this->getFilterBookCollection($filters);

        return BookCollectionResource::collection($book_collection);


        // 男频书单
        // 女频书单
        // 我的书单

    }

    protected function getFilterBookCollection(BookCollectionFilter $filters){

        $limit = Input::get('limit') ?: 20;

        $builder = BookCollection::query()->filter($filters);

        return $builder->paginate($limit);


    }

    /**
     *
     * @api {post} /book_collections 新建书单
     * @apiName Books post book_collections
     * @apiGroup BookCollection
     *
     * @apiParam {String} title 书单的标题
     * @apiParam {String} bio 书单的描述
     * @apiParam {String} [cover_url] 书单的封面
     * @apiParam {String} [gender] [0]男频和[1]女频
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/book_collections
     *
     */
    public function store(Request $request){

        $this->validate($request,[
            'title' => 'required',
            'bio' => 'required',
            'cover_url' => 'url',
            'gender' => 'integer|between:0,1'
        ]);

        Auth::user()->bookCollection()->create($request->all());

        return $this->message('创建书单成功');

    }

    /**
     *
     * @api {delete} /book_collections/:id 删除书单
     * @apiName Books delete book_collections
     * @apiGroup BookCollection
     *
     * @apiParam {String} id 书单的id
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/book_collections/:id
     *
     */
    public function destroy(BookCollection $collection){

        $this->authorize('destroy',$collection);
        $collection->delete();
        return $this->message('删除成功');
    }

}
